<template>
  <el-dialog :title="props.id !== undefined ? '编辑角色':'新增角色'"
             :model-value="modelValue"
             @close="closed"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
      size="large"
      status-icon
    >
      <el-form-item label="角色名称:" prop="name">
        <el-input v-model="ruleForm.name" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述:" prop="description">
        <el-input v-model="ruleForm.description" type="text" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closed(ruleFormRef)">取消</el-button>
      <el-button @click="reset(ruleFormRef)">重置</el-button>
      <el-button type="primary" @click="onComfirm(ruleFormRef)">{{props.id !== undefined ? '确认修改':'确认添加'}}</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onBeforeUpdate } from 'vue'
import { roleAdd, roleDetail, roleEdit } from '../../../../api/role'
import { FormInstance, FormRules } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  id: {
    type: String,
    required: false
  }
})
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  name: '',
  description: ''
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input name', trigger: 'blur' },
    { min: 3, max: 10, message: 'Length should be 3 to 10', trigger: 'blur' }
  ],
  description: [
    {
      required: true,
      message: 'Please input description',
      trigger: 'blur'
    }
  ]
})
const emits = defineEmits(['update:modelValue', 'updateData'])
const onComfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) return
    if (props.id) {
      await roleEdit({
        id: props.id,
        name: ruleForm.name,
        description: ruleForm.description
      })
    } else {
      await roleAdd({
        name: ruleForm.name,
        description: ruleForm.description
      })
    }
    emits('updateData')
    closed(formEl)
  })
}
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const closed = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emits('update:modelValue', false)
}
onBeforeUpdate(async () => {
  if (props.id) {
    const res = await roleDetail(props.id)
    ruleForm.name = res.name
    ruleForm.description = res.description
  }
})
</script>
<style scoped lang="scss">
</style>
